<template>
  <div class="log-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="输入用户名搜索" style="width: 200px;" class="filter-item" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-date-picker
        class="filter-item"
        v-model="listQuery.date"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :default-time="['00:00:00', '23:59:59']"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        Search
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        style="float: right;"
        icon="el-icon-download"
        @click="handleDownload"
      >
        Export
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="logList"
      border
      fit
      max-height="550px"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作者" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.operator }}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.type | typeFilter">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.operation }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="150px">
        <template slot-scope="{row}">
          {{ row.remark }}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="paging-box"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.page"
      :page-sizes="[5,15, 20, 50]"
      :page-size="listQuery.size"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
      layout="prev, pager, next,sizes, total, jumper"
    ></el-pagination>
  </div>
</template>

<script>
  export default {
    name: "SystemLog",
    filters: {
      statusFilter(status) {
        const statusMap = {
          success: 'success',
          failure: 'danger',
          other: 'info'
        }
        return statusMap[status] || statusMap["other"]
      },
      typeFilter(status) {
        const statusMap = {
          login: 'info',
          logout:'info',
          other: 'info'
        }
        return statusMap[status] || statusMap["other"]
      }
    },
    data(){
      return{
        listQuery: {
          keyword:null,
          time:null,
          status:null,
          date:[],
          page: 1,
          size: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        total:100,
        listLoading:false,
        tableKey: 0,
        logList:[],
        statusOptions:[
          { key: 'success', display_name: '成功' },
          { key: 'failure', display_name: '失败' },
          { key: 'other', display_name: '其他' }
        ],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        downloadLoading: false
      }
    },
    mounted(){
      this.getList();
    },
    methods:{
      getList(){
        this.listLoading = true
        this.getRequest("/log/list",this.listQuery).then((res)=>{
          console.log(res)
          this.logList=res.records;
          this.listQuery.page=res.current;
          this.listQuery.size=res.size;
          this.total=res.total;
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          try{
            const tHeader = ['operator','operation','time', 'type', 'ip', 'status','remark']
            const filterVal =  ['operator','operation','time', 'type', 'ip', 'status','remark']
            const data = this.formatJson(filterVal)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '日志-' + this.$moment().format("yyyy-MM-DD")
            })
          }catch (e) {
            console.log(e)
          }finally {
            this.downloadLoading = false
          }
        })
      },
      formatJson(filterVal) {
        return this.logList.map(v => filterVal.map(j => {
            return v[j]
        }))
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      handleSizeChange(val) {
        this.listQuery.size = val;
        console.log(`每页 ${val} 条`);
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        console.log(`当前页: ${val}`);
        this.getList();
      }
    }
  }
</script>

<style>
  .log-container{
    text-align: left;
  }
  .el-pagination{
    margin: 10px;
  }
  .el-pagination.is-background .btn-prev{
    padding: 0 5px;
  }
  .el-pagination.is-background  .btn-next{
    padding: 0 5px;
  }
  .el-pagination button:disabled{
    display: none;
  }
</style>